//
//  Tool.m
//  oschina
//
//  Created by wangjun on 12-3-13.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "Tool.h"
#import <sys/utsname.h>
#import <CommonCrypto/CommonDigest.h> // Need to import for CC_MD5 access
#import "AppDelegate.h"

@implementation Tool

//判断表情
+ (BOOL)isContainsEmoji:(NSString *)string {
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     isEomji = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 isEomji = YES;
             }
             
         } else {
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 isEomji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 isEomji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 isEomji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 isEomji = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                 isEomji = YES;
             }
         }
     }];
    
    return isEomji;
}

+ (void)setCache:(NSString *)key value:(id)value{
    NSUserDefaults * setting = [NSUserDefaults standardUserDefaults];
    [setting setObject:value forKey:key];
    [setting synchronize];
}

+ (NSString *)getCache:(NSString *)key{
    NSUserDefaults * settings = [NSUserDefaults standardUserDefaults];
    NSString *value = [settings objectForKey:key];
    return value;
}

+ (void)removeCache:(NSString *)key
{
    NSUserDefaults * settings = [NSUserDefaults standardUserDefaults];
    [settings removeObjectForKey:key];
    [settings synchronize];
}

+ (void)setFileCache:(NSString *)key value:(id)content{

	NSString *filePath = [self getFileCachePath:key];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:NULL];
    }
    NSDictionary *dictdata = @{@"FileContent":content,@"FileTime":[NSNumber numberWithLong:(long)[[NSDate date] timeIntervalSince1970]]};
    
    NSMutableData *data = [[NSMutableData alloc] init];
    
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:dictdata forKey:@"nsdatakey"];
    [archiver finishEncoding];
    
    //NSLog(@"dictdata:%@",dictdata);
    
    // Can't use defaultManager another thread
    NSFileManager *fileManager = [[NSFileManager alloc] init];
   [fileManager createFileAtPath:filePath contents:data attributes:nil];
 
}

+ (id)getFileCache:(NSString *)key
{
     NSString *filePath = [self getFileCachePath:key];
     NSData *filedata = [NSData dataWithContentsOfFile:filePath options:0 error:nil];
    if (filedata == nil) {
        return nil;
    }
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:filedata];
    NSDictionary *dict = [unarchiver decodeObjectForKey:@"nsdatakey"];
    id entity = [dict objectForKey:@"FileContent"];
    [unarchiver finishDecoding];
    
    return entity;
}

+ (NSString *)getFileCachePath:(NSString *)key{
    NSString *dirname = @"artron.cache";
    
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:dirname];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:filePath
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:NULL];
    }
 
    filePath = [filePath stringByAppendingPathComponent:[self getMd5_32Bit_String:key]];
    return filePath;
}

+ (NSString *)setFileDocumentPath:(NSString *)key
{
    NSString *dirname = @"artron.cache";
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:dirname];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:filePath
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:NULL];
        //禁止iCloud备份
        [self addSkipBackupAttributeToItemAtURL:[[NSURL alloc]initFileURLWithPath:filePath isDirectory:YES]];
    }
    
    filePath = [filePath stringByAppendingPathComponent:[self getMd5_32Bit_String:key]];
    
    
    return filePath;
}
/**
 *  禁止iCloud备份，用于向document存储东西时使用
 *
 *  @param URL 存储URL
 *
 *  @return 成功与否
 */
+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    NSError *error = nil;
    BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
                                  forKey: NSURLIsExcludedFromBackupKey error: &error];
    if(!success){
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
    }
    return success;
}


+ (NSString *)getMd5_32Bit_String:( NSString *)srcString{
    
    const char *cStr = [srcString UTF8String ];
    
    unsigned char digest[ CC_MD5_DIGEST_LENGTH ];
    
    CC_MD5 ( cStr, (CC_LONG)strlen (cStr), digest );
    
    NSMutableString *result = [ NSMutableString stringWithCapacity : CC_MD5_DIGEST_LENGTH * 2 ];
    
    for ( int i = 0 ; i < CC_MD5_DIGEST_LENGTH ; i++)
        
        [result appendFormat : @"%02x" , digest[i]];
    //NSLog(@"注册时的密码：%@", result);
    
    return result;
}


+ (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}

+ (int)getCnCharNum:(NSString *)text{
    
    //NSString *temp = nil;
    int num = 0;
    for(int i =0; i < [text length]; i++)
    {
        //temp = [text substringWithRange:NSMakeRange(i, 1)];
        unichar a = [text characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){
            num += 1;
        }
        //NSLog(@"第%d个字是:%@",i,temp);
    }
    return num;
    
}

+ (BOOL)validateMobile:(NSString *)mobile{
    
    NSString *phoneRegex = @"^(1[3456789]{1})\\d{9}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //NSLog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:mobile];
}


+(int)getRandomNumber:(int)from to:(int)to

{
//    NSLog(@"from:%d",from);
//    NSLog(@"to:%d",to);
    if (from < to) {
        return (int)(from + (arc4random() % (to - from + 1))); //+1,result is [from to]; else is [from, to)!!!!!!!
    }else{
        return (int)(to + (arc4random() % (from - to + 1))); //+1,result is [from to]; else is [from, to)!!!!!!!
    }
}

//计算输入本文的长度
+ (int)textLength:(NSString *)text
{
    float number = 0.0;
    for (int index = 0; index < [text length]; index++)
    {
        NSString *character = [text substringWithRange:NSMakeRange(index, 1)];
        
        if ([character lengthOfBytesUsingEncoding:NSUTF8StringEncoding] == 3)
        {
            number++;
        }
        else
        {
            number = number + 0.5;
        }
    }
    
    return ceil(number);
}

+ (CGSize)getSizeWithString:(NSString *)string font:(UIFont *)font
{
    return [self getSizeWithString:string font:font blanksize:75];
}

+ (CGSize)getSizeWithString:(NSString *)string font:(UIFont *)font blanksize:(float)blanksize
{
    CGRect rect = CGRectZero;
    if (string && [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]>0&&![string isKindOfClass:[NSNull class]]) {
        NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:string attributes:attributes];
       
        rect = [attributedText boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - blanksize, 50000.0f) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil];
    }
    return rect.size;
}

+(CGSize)getSizeWithString:(NSString *)string font:(UIFont *)font withWidth:(CGFloat)width
{
    CGRect rect = CGRectZero;
    if (string && [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]>0&&![string isKindOfClass:[NSNull class]]) {
        NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:string attributes:attributes];
        
        rect = [attributedText boundingRectWithSize:CGSizeMake(width, 50000.0f) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil];
    }
    return rect.size;
}

+ (CGSize)getSizeWithString:(NSString *)string font:(UIFont *)font withHeight:(CGFloat)height
{
    CGRect rect = CGRectZero;
    if (string && [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]>0&&![string isKindOfClass:[NSNull class]]) {
        NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:string attributes:attributes];
        
        rect = [attributedText boundingRectWithSize:CGSizeMake(5000.0f, height) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    }
    return rect.size;
}


//得到中英文混合字符串长度
+ (NSInteger)getToInt:(NSString*)strtemp
{
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8);
    NSData* da = [strtemp dataUsingEncoding:enc];
    return [da length];
}


+ (NSDictionary *)getDicFromJson:(id)json{
    id dic = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",json] dataUsingEncoding:NSUTF8StringEncoding]
                                          options:NSJSONReadingAllowFragments
                                            error:nil];
    
    if ([dic isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dict = (NSDictionary *)dic;
        if (dict.count) {
            return dict;
        }
    }
    
    return nil;
}

+ (NSArray *)getArrayFromJson:(id)json{
    id dic = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",json] dataUsingEncoding:NSUTF8StringEncoding]
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
    
    
    if ([dic isKindOfClass:[NSArray class]]) {
        NSArray *array = (NSArray *)dic;
        if (array.count) {
            return array;
        }
    }
    return nil;
}

+ (NSString *)getStringFromJson:(id)json{
    if ([json isKindOfClass:[NSString class]]) {
        return [NSString stringWithFormat:@"%@",json];
    }
    return nil;
}

//+ (void)showTextHUD:(NSString *)text andView:(UIView *)view labelTextColor:(UIColor *)labelTextColor
//{
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
//    if (labelTextColor) hud.labelColor = labelTextColor;
//    hud.mode = MBProgressHUDModeText;
//    hud.labelText = text;
//    hud.margin = 30.f;
//    hud.yOffset = -50.f;
//    hud.removeFromSuperViewOnHide = YES;
//    [hud hide:YES afterDelay:1];
//    
//}

+ (void)saveObjectToSystem:(id)object forKey:(NSString*)key
{
    [[NSUserDefaults standardUserDefaults] setObject:object forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (id)getObjectFromSystemWithKey:(NSString*)key
{
    return [[NSUserDefaults standardUserDefaults] stringForKey:key];
}

+ (NSString *)getFileMd5:(NSString *)path{
    
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
    if( handle== nil ) {
        return nil;
    }
    CC_MD5_CTX md5;
    CC_MD5_Init(&md5);
    BOOL done = NO;
    while(!done)
    {
        NSData* fileData = [handle readDataOfLength: 256 ];
        CC_MD5_Update(&md5, [fileData bytes], (int)[fileData length]);
        if( [fileData length] == 0 ) done = YES;
    }
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(digest, &md5);
    NSString* s = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                   digest[0], digest[1],
                   digest[2], digest[3],
                   digest[4], digest[5],
                   digest[6], digest[7],
                   digest[8], digest[9],
                   digest[10], digest[11],
                   digest[12], digest[13],
                   digest[14], digest[15]];
    
    return s;
    
}


+ (NSDictionary *)getParmsFromUrl:(NSURL *)url{
    
    NSMutableDictionary *queryStrings = [[NSMutableDictionary alloc] init];
    for (NSString *qs in [url.query componentsSeparatedByString:@"&"]) {
        // Get the parameter name
        NSString *key = [[qs componentsSeparatedByString:@"="] firstObject];
        // Get the parameter value
        NSString *value = [[qs componentsSeparatedByString:@"="] objectAtIndex:1];
        value = [value stringByReplacingOccurrencesOfString:@"+" withString:@" "];
        value = [value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        queryStrings[key] = value;
    }
    return queryStrings;
}

+ (NSString *)getCurrentVersion
{
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    return version;
}
/**
 *  解码base64
 *
 *  @param string 文字
 */
//+ (NSString*)decodeBase64String:(NSString* )input {
//    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//    if (data == nil) {
//        return @"";
//    }
//    data = [GTMBase64 decodeData:data];
//    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    return base64String;
//}
/**
 *  编码64
 *
 *  @param input 文字
 */
//+ (NSString *)encodeBase64String:(NSString *)input
//{
//    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//    if (data == nil) {
//        return @"";
//    }
//    data = [GTMBase64 encodeData:data];
//    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    return base64String;
//}
/**
 *  验证一段文字是否都为数字
 *
 *  @param string 文字
 *
 *  @return YES / NO
 */
+ (BOOL)isAllNumberString:(NSString *)string
{
    NSString * regex = @"^[0-9]*$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}
/**
 *  验证手机号码
 *
 *  @param mobileNum 手机号
 *
 *  @return 是否为正确的
 */
+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    NSString * MU = @"1[0-9]{10}";
    NSPredicate *regextestMU = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MU];
    if ([regextestMU evaluateWithObject:mobileNum] == YES) {
        return YES;
    }else
    {
        return NO;
    }
}
/**
 *  截屏成为图片
 *
 *  @return 返回图片
 */
+ (UIImage *)snapshot
{
    UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow];
    UIGraphicsBeginImageContextWithOptions(screenWindow.frame.size,YES,0);
    [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}

+ (BOOL)validateStringIsEmpty:(NSString *)str {
    if (str && str.length>0) {
        return NO;
    }
    
    return YES;
}
@end
